package cn.tedu.store.controller;

import cn.tedu.store.service.IWechatService;
import cn.tedu.store.util.JsonResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@RestController // 表示一个控制器类且所有请求结果响应正文
@RequestMapping("wechat")
public class WechatController extends BaseController {
	IWechatService wechatService;
	//private static Logger logger;
	public static void main(String[] args) {
		// run in a second
		final long timeInterval = 1000;
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				while (true) {
					System.out.println("Hello !!");
					try {
						Thread.sleep(timeInterval);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		Thread thread = new Thread(runnable);
		thread.start();
	}

	@GetMapping("/")
	public JsonResult<Void> wechatSecurity(HttpServletRequest request, HttpServletResponse response,
			String signature,
			String timestamp,
			String nonce,
			String echostr) {
		System.err.println("收到了来自微信的验证get请求");
		try {
			if (wechatService.checkSignature(signature, timestamp, nonce)) {
				PrintWriter out = response.getWriter();
				out.print(echostr);
				out.close();
			} else {
				System.err.println("这里存在非法请求！");
			}
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		// wechatService.checkSignature(signature, timestamp, nonce);
		return new JsonResult<>(SUCCESS);
	}
}
